﻿using Microsoft.AspNetCore.Mvc;
using ProjectScheduling_web.dao;
using ProjectScheduling_web.model;
using ProjectScheduling_web.model.Enums;
using SqlSugar;

namespace ProjectScheduling_web.Controllers.U
{
    public class DictionaryController : BController
    {
        private static readonly DictionaryDataDao @base = DictionaryDataDao.Base;
        [HttpGet]
        public IActionResult Search(EnumDictionaryCategory id)
        {
            return Success(@base.FindAll(it => it.Category == id));
        }
        [HttpPost]
        public IActionResult Add([FromBody] DictionaryData req)
        {
            if (req == null) return Fail("数据有误");
            #region 验证数据准确性
            if (req.Category == 0) return Fail("获取分类信息错误");
            if (string.IsNullOrEmpty(req.Name)) return Fail("键不能为空");
            if (req.Value <= 0) return Fail("值有误");
            if (@base.Exists(it => (it.Name == req.Name || it.Value == req.Value) && it.Category == req.Category))
                return Fail("当前数据已存在，请勿重复添加");
            #endregion
            @base.Add(new DictionaryData
            {
                Name = req.Name,
                Value = req.Value,
                Category = req.Category
            });
            return Success("创建成功");
        }
        [HttpPost]
        public IActionResult Update([FromBody] DictionaryData req)
        {
            if (req == null) return Fail("数据有误");
            #region 验证数据准确性
            if (string.IsNullOrEmpty(req.Name)) return Fail("键不能为空");
            if (req.Value <= 0) return Fail("值有误");
            if (req.Id == 0) return Fail("获取数据字典信息有误");
            var obj = @base.Find(req.Id);
            if (obj == null) return Fail("当前数据字典不存在");
            if (@base.Exists(z => z.Id != req.Id && z.Category == req.Category && (z.Name == req.Name || z.Value == req.Value)))
                return Fail("当前分类中键值不能重复");
            #endregion
            obj.Name = req.Name;
            obj.Value = req.Value;
            @base.Update(obj, it => new { it.Name, it.Value });
            return Success("修改成功");
        }
        [HttpGet]
        public IActionResult Remove(int id)
        {
            var result = @base.Delete(id);
            return result > 0 ? Success("删除成功") : Fail("删除失败");
        }
        [HttpGet]
        public IActionResult Enums(EnumDictionaryCategory id)
        {
            var list = @base.FindAll(it => it.Category == id);
            return Success(list.Select(it => new IdName(it.Value, it.Name ?? "")).ToList());
        }
    }
}
